package com.gwc.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

@WebServlet(
        urlPatterns = {"/httpServletRequest2"}
)
public class HttpServletRequest2 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取键值对形式的参数
        // 根据参数名获取单个参数值
        String userName = req.getParameter("userName");
        System.out.println("userName: "+userName);
        String password = req.getParameter("password");
        System.out.println("password: "+password);
        // 根据参数名获取多个参数值
        String[] hobbies = req.getParameterValues("hobby");
        System.out.println("hobby: "+ Arrays.toString(hobbies));

        // 通过while自动获取所有参数名
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()){
            String parameter = parameterNames.nextElement();
            // 无论是单值还是多值，都返回一个数组
            String[] parameterValues = req.getParameterValues(parameter);
            if (parameterValues.length == 1){
                System.out.println(parameter+": "+parameterValues[0]);
            }else {
                System.out.println(parameter+": "+Arrays.toString(parameterValues));
            }
        }

        // 将所有键值对保存到一个map集合里
        Map<String, String[]> parameterMap = req.getParameterMap();
        // 变成可迭代的对象
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            String key = entry.getKey();
            String[] value = entry.getValue();
            if(value.length == 1){
                System.out.println(key+": "+value[0]);
            }else {
                System.out.println(key+": "+Arrays.toString(value));
            }
        }
    }
}
